package com.coy.web.config;

import com.coy.web.common.exception.BizResultCode;
import com.coy.web.common.exception.LoginException;
import com.coy.web.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.session.Session;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * session拦截处理类
 */
@Slf4j
public class SessionHandlerInterceptor extends HandlerInterceptorAdapter {

    private final static Logger logger = LoggerFactory.getLogger(SessionHandlerInterceptor.class);

    /**
     * debug 模式，仅仅用于开发测试阶段
     */
    @Value("${app.session.debug.mode:false}")
    private boolean debugMode;

    @Value("${spring.session.headerName}")
    String sessionHeaderName;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse response, Object handler)
            throws Exception {
        if (debugMode) {
            logger.warn("跳过session拦截器，url={}", req.getRequestURI());
            return true;
        }

        // 当session不存在时不创建session
        HttpSession session = req.getSession(false);
        // 判断用户是否登录
        if (null == session) {
            logger.error("用户未登录， url={}, sid={}", req.getRequestURI(), req.getHeader(sessionHeaderName));
            throw new LoginException(BizResultCode.ERR_NOT_LOGIN);
        }

        if (logger.isDebugEnabled()) {
            Enumeration<String> names = session.getAttributeNames();
            while (names.hasMoreElements()) {
                String key = names.nextElement();
                Object value = session.getAttribute(key);
                logger.debug("key={},value={}", key, value);
            }
        }

        logger.info("SessionId = " + session.getId());
        if (session instanceof Session) {
            if (((Session) session).isExpired()) {
                logger.error("用户登陆已过期， url={}, sid={}", req.getRequestURI(), req.getHeader(sessionHeaderName));
                throw new LoginException(BizResultCode.ERR_NOT_LOGIN);
            }
        }

        com.coy.web.zax.feign.dto.UserInfoDTO userInfoDTO = SessionUtil.getUser(session);
        if (null == userInfoDTO) {
            logger.error("session 中不存在用户信息，请重新登录， url={}, sid={}", req.getRequestURI(),
                    req.getHeader(sessionHeaderName));
            throw new LoginException(BizResultCode.ERR_NOT_LOGIN);
        }
        return true;
    }

    /**
     * 输出结果
     */
    private void output(HttpServletResponse response, String code, String message) throws Exception {
        String result = "{\"retcode\":\"" + code + "\",\"retmsg\":\"" + message + "\",\"data\":null}";
        response.setHeader("content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println(result);
    }
}